<template>
  <div class="form-single-fragment" style="position: relative">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      size="mini"
      label-position="right"
    >
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="24">
          <el-col :span="12">
            <el-form-item label="线索名称" prop="clueName">
              <el-input
                class="input-item"
                v-model="ruleForm.clueName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="customerName">
              <el-input
                class="input-item"
                v-model="ruleForm.customerName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业联系人" prop="contacts">
              <el-input
                class="input-item"
                v-model="ruleForm.contacts"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业联系电话" prop="telephone">
              <el-input
                class="input-item"
                v-model="ruleForm.telephone"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="districtCode">
              <el-cascader
                v-model="ruleForm.districtCode"
                ref="ref_areaCodes"
                :options="areaCodelist"
                :props="areaCodeprops"
                clearable
                @change="areaCodesChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址">
              <el-input
                class="input-item"
                v-model="ruleForm.detailedAddress "
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="业务类型" prop="businessType">
              <el-cascader v-model="businesstypeId"
                ref="ref_business"
                :options="businesstypeTree"
                :props="businesstProps"
                :show-all-levels="false"
                clearable
                @change="businessChange"></el-cascader>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="企业属性">
              <el-select
                v-model="ruleForm.productIntention"
                clearable
                placeholder="请选择"
              >
                <el-option label="国有企业" value="国有企业"></el-option>
                <el-option label="国有控股" value="国有控股"></el-option>
                <el-option label="外资企业" value="外资企业"></el-option>
                <el-option label="合资企业" value="合资企业"></el-option>
                <el-option label="私营企业" value="私营企业"></el-option>
                <el-option label="事业单位" value="事业单位"></el-option>
                <el-option label="国家行政机关" value="国家行政机关"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线索来源">
              <el-select
                v-model="ruleForm.clueSource"
                clearable
                placeholder="请选择"
              >
                <el-option label="电话来访" value="电话来访"></el-option>
                <el-option label="客户介绍" value="客户介绍"></el-option>
                <el-option label="独立开发" value="独立开发"></el-option>
                <el-option label="社会公开信息" value="社会公开信息"></el-option>
                <el-option label="其它" value="其它"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型">
              <el-input
                v-model="ruleForm.projectType"
                placeholder="请输入"
                clearable
                maxlength="10"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务类型" prop="businessTypeList">
              <el-checkbox-group v-model="ruleForm.businessTypeList" @change="handleSelectBusinessType">
                <el-checkbox v-for="item in businesstypeTree" :key="item.id" :label="item.idStr">{{item.businessName}}</el-checkbox>
              </el-checkbox-group>
              <el-input
                  v-if="(ruleForm.businessType).indexOf('1475380487239405571') != '-1'"
                  style="width: 35%"
                  v-model="ruleForm.otherType"
                  placeholder="请输入"
                  clearable
                ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="线索内容" prop="clueContent">
              <el-input
                type="textarea"
                rows="4"
                class="input-item"
                v-model="ruleForm.clueContent"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0">
              <el-button size="mini" @click="onCancel(false)">取消</el-button>
              <el-button type="primary" size="mini" @click="submitForm()"
                >确定</el-button
              >
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Cluemanagement } from '@/api/commercial.js';
import { Businesstype } from '@/api/business.js';
import { findTreeNodePath } from '@/utils';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
export default {
  name: 'Clueadd',
  props: {
    clueId: {
      default: undefined
    }
  },
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入企业联系电话'));
      } else if (!/^(\d{1,4})-(\d{6,8})$/.test(value) && !/^1\d{10}$/.test(value)) {
        callback(new Error('企业联系电话格式不正确'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      isShowloading: false,
      userId: null,
      businesstypeTree: [],
      businesstypeId: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true
      },
      areaCodelist: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      ruleForm: {
        clueName: '',
        businessTypeList: [],
        businessType: '',
        customerName: '',
        productIntention: '',
        contacts: '',
        telephone: '',
        clueSource: '',
        clueContent: '',
        projectType: ''
      },
      rules: {
        clueName: [{ required: true, message: '请输入', trigger: 'blur' }],
        businessTypeList: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        // telephone: [{ validator: checkPhone, trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入企业联系电话', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur' }],
        customerName: [{ required: true, message: '请输入', trigger: 'blur' }],
        clueContent: [{ required: true, message: '请输入', trigger: 'blur' }],
        districtCode: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      businessType: []
    };
  },
  created () {
    this.loadareaCodelistDict();
  },
  computed: {
    isEdit () {
      return this.clueId != null && this.clueId !== '';
    }
  },
  mounted () {
    if (this.isEdit) {
      this.loadCluedetail();
    } else {
      this.loadbusinesstypeTree();
    }
  },
  methods: {
    handleSelectBusinessType (val) {
      console.log(val.join(','))
      // this.$set(this.ruleForm, 'businessType', val.join(','))
      this.ruleForm.businessType = val.join(',')
    },
    /**
     * 线索详情
     */
    loadCluedetail () {
      let params = this.clueId;
      return new Promise((resolve, reject) => {
        Cluemanagement.detail(this, params)
          .then((res) => {
            res.data.businessTypeList = res.data.businessType.split(',')
            this.ruleForm = res.data;
            this.loadbusinesstypeTree();
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this)
          .then((res) => {
            this.businesstypeTree = res.data;
            if (this.isEdit) {
              this.businesstypeId = findTreeNodePath(
                res.data,
                this.ruleForm.businessType
              );
            }
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    businessChange () {
      let info = this.businesstypeId;
      let length = info.length - 1;
      this.ruleForm.businessType = info[length];
      this.$refs['ref_business'].dropDownVisible = false;
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this)
          .then((res) => {
            let areaCodelist = res.data;
            let areaCodelistnew = [];
            areaCodelist.forEach((item, index) => {
              if (!item.parentId) {
                item.children = [];
                areaCodelistnew.push(item);
              }
            });
            areaCodelistnew.forEach((item1, index1) => {
              let info = areaCodelist.find((item2, index2) => {
                return item1.id === item2.parentId;
              });
              if (info) {
                item1.children = [];
                areaCodelist.forEach((item3, index3) => {
                  if (item1.id === item3.parentId) {
                    item1.children.push(item3);
                  }
                });
              } else {
                item1.children = null;
              }
            });
            areaCodelistnew.forEach((item4, index4) => {
              if (item4.children) {
                item4.children.forEach((item5, index5) => {
                  let info2 = areaCodelist.find((item6, index6) => {
                    return item5.id === item6.parentId;
                  });
                  if (info2) {
                    item5.children = [];
                    areaCodelist.forEach((item7, index7) => {
                      if (item5.id === item7.parentId) {
                        item5.children.push(item7);
                      }
                    });
                  } else {
                    item5.children = null;
                  }
                });
              }
            });
            this.areaCodelist = areaCodelistnew;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 选择行政区划
     */
    areaCodesChange (val) {
      console.log(val)
      this.$refs['ref_areaCodes'].dropDownVisible = false;
    },
    /**
     * 提交表单
     */
    submitForm () {
      console.log(this.ruleForm)
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = this.ruleForm;
          if (this.isEdit) {
            // 修改
            return new Promise((resolve, reject) => {
              Cluemanagement.update(this, params)
                .then((res) => {
                  this.$message({
                    showClose: true,
                    message: '修改成功！',
                    type: 'success'
                  });
                  this.onCancel(true);
                })
                .catch((e) => {
                  reject(e);
                });
            });
          } else {
            // 添加
            return new Promise((resolve, reject) => {
              Cluemanagement.add(this, params)
                .then((res) => {
                  this.$message({
                    showClose: true,
                    message: '添加成功！',
                    type: 'success'
                  });
                  this.onCancel(true);
                })
                .catch((e) => {
                  reject(e);
                });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
};
</script>

<style scoped>
h3 {
  border-bottom: 1px solid #e9e9eb;
  padding: 0 0 10px;
}
.table_container {
  margin: 10px 0;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.form-single-info .el-cascader--mini {
  width: 100%;
}
</style>
